<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      
    </style>
</head>
<body>
    <center>
        <canvas id="myCanvas" onmousedown="down(event)" onmouseup="up()">

        </canvas>
    </center>
    
</body>
<script>
    /** @type {HTMLCanvasElement} */
    let myCanvas=document.querySelector("#myCanvas");
    myCanvas.width=900;
    myCanvas.height=600;
    myCanvas.style.border="1px solid red";
    let ctx=myCanvas.getContext("2d");

    function down(event){
        //鼠标按下左键时执行的代码
        //获取鼠标的坐标:x,y 
        ctx.beginPath(); 
        let obj=myCanvas.getBoundingClientRect();
        let x=event.x-obj.left;
        let y=event.y-obj.top;             
        ctx.moveTo(x,y);
        myCanvas.onmousemove=move;//将move方法和鼠标移动事件进行绑定
    }

    function move(event){
        //鼠标按住左键之后,再移动时执行的代码
        //鼠标释放左键之后,再移动时不能执行的代码
        //获取鼠标移动后的坐标,x,y
        //作用是画线
        let obj=myCanvas.getBoundingClientRect();
        let x=event.x-obj.left;
        let y=event.y-obj.top;  
        ctx.lineTo(x,y)
        ctx.stroke();
    }

    function up(){
        //鼠标释放左键之后时执行的代码
        //将move方法和鼠标移动事件解绑
        myCanvas.onmousemove=null;
    }


    
</script>
</html>